package io;

import java.io.*;
import java.util.Scanner;

public class IODemo15 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径: ");
        String rootPath = scanner.next();
        System.out.println("请输入要查询的词: ");
        String word = scanner.next();

        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()) {
            System.out.println("输入的要搜索的路径不正确!");
            return;
        }

        scanDir(rootFile,word);
    }

    private static void scanDir(File rootFile, String word) {
        File[] files = rootFile.listFiles();
        if (files == null) {
            return;
        }
        for (File f : files) {
            System.out.println("当前遍历到: " + f.getAbsolutePath());
            if (f.isFile()) {
                //在文件内容中搜索
                searchInFile(f,word);
            } else if (f.isDirectory()) {
                //递归遍历
                scanDir(f,word);
            }
        }
    }

    private static void searchInFile(File f, String word) {
        //通过这个方法在文件内部进行搜索
        //1.把这个文件内容读取出来
        try(InputStream inputStream = new FileInputStream(f)) {
            StringBuilder stringBuilder = new StringBuilder();
            while (true) {
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if (n == -1) {
                    break;
                }
                //此处只是读取出文件的一部分,需要把文件内容整体拼接在一起
                String s = new String(buffer,0,n);
                stringBuilder.append(s);
            }

            //加了打印内容后,可以看到文件内容
            System.out.println("文件内容: " + stringBuilder);

            //当文件读取完毕,循环结束之后,此时 stringBuilder 就是包含整个内容的字符串了
            if (stringBuilder.indexOf(word) == -1) {
                //没找到要返回
                return;
            }
            //找到了,打印文件的路径
            System.out.println("找到了" + "word" + "存在于" + f.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
